package se.perp.c4.control;

import java.awt.Container;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import se.perp.c4.control.iface.IMessenger;
import se.perp.c4.control.iface.ISpecialCardListener;
import se.perp.c4.control.iface.ITerritorySelectionListener;
import se.perp.c4.model.Actor;
import se.perp.c4.model.Territory;
import se.perp.c4.model.Territory.ETerritory;
import se.perp.c4.model.TerritoryCollection;
import se.perp.c4.net.Message;
import se.perp.c4.ui.GamePiece;
import se.perp.c4.ui.MainWindow;
import se.perp.c4.ui.PieceCollection;
import se.perp.c4.ui.SpecialCard;
import se.perp.c4.ui.TerritorySelectionPanel;
import static se.perp.c4.model.Actor.Side.*;

public class PalantirRevealHandler implements
        ITerritorySelectionListener, ISpecialCardListener {

    private final PieceCollection pieceColl;
    private final TerritoryCollection terrColl;
    private List<GamePiece> revealed = new LinkedList<GamePiece>();
    private final MainWindow mainWindow;
    private Container savedPanel;
    private final IMessenger conn;

    public PalantirRevealHandler(MainWindow mw, PieceCollection pc,
            TerritoryCollection tc, IMessenger conn) {
        mainWindow = mw;
        pieceColl = pc;
        terrColl = tc;
        this.conn = conn;
    }

    public void territorySelected(ETerritory et) {

        Territory t = terrColl.get(et);
        for (Actor a : t.getOccupants()) {
            GamePiece gp = pieceColl.get(a.who);
            gp.setKnown(true);
            revealed.add(gp);
        }

        mainWindow.setContainer(savedPanel);
        mainWindow.hideMessage(DARK);
        mainWindow.repaint();
        conn.sendMessage(Message.newPalantirPlayed(et));
    }

    public void cardClicked(SpecialCard c) {
        List<ETerritory> revealable = new ArrayList<ETerritory>();
        for (Territory t : terrColl) {
            if (t.isOccupiedByLight() && t.which != ETerritory.SHIRE) {
                revealable.add(t.which);
            }
        }

        if (revealable.isEmpty()) {
            throw new RuntimeException("Erroneous invocation of Palantir!");
        }

        c.setEnabled(false);

        savedPanel = mainWindow.getContainer();
        mainWindow.setMessage(DARK, "Select region to reveal.");
        mainWindow.setContainer(new TerritorySelectionPanel(
                savedPanel,
                this,
                revealable));

        mainWindow.repaint();
    }
}
